import { setStorage, getStorage } from '../common/utils'
import { useHttp } from './http'

export let wxLogin = (callback) => {
    let code = '';

    wx.login({
      success: (res) => {
        code = res.code;
      }
    })
    
    wx.getUserProfile({
      desc: '用于完善会员资料',
      success: (userInfoRes) => {
        setStorage('user_info', userInfoRes);

        let option = {
          url: 'login',
          data: {
            code
          }
        }

        wx.showLoading({
            mask: true,
            title: '登入中'
        })

        useHttp('POST', option).then(res => {
            if(res.state) {
              //登入成功
              setStorage('token', res.data);

              callback&&callback(userInfoRes);
              
            }else{
                wx.showToast({
                    icon: 'none',
                    title: '登入失败，请稍后再试'
                })
            }

            wx.hideLoading();
        }).catch(error => {

          wx.showToast({
            icon: 'none',
            title: '登入失败，请稍后再试'
          })

          wx.hideLoading();
        })

        
      },
      fail: (err) => {
        wx.hideLoading();
        
        wx.showModal({
          showCancel: false,
          title: '提示',
          content: '需要通过授权才能继续，请重新点击登录并授权！'
        })
      }
    })
}

export let verifyToken = async () => {

  let setting = {
    url: 'verifyToken',
    data: {}
  }

  return useHttp("POST", setting).then(result => {
    if(result.code === 0){
      return true;
    }else{
      return false
    }
  }).catch(error => {
    return error
  })

}

export let placeOrder = async (callback) => {
  let token = await getStorage('token');
  
  let option = {
    url: 'placeOrder',
    data: {
      PayType: wx,
      OrderAmount: 0.01,
      CompanyCode: 'gzjs',
      subOpenId: token.subOpenId
    }
  }

  useHttp('POST', option).then(res => {
    if(res.state) {
      callback&&callback(res.data);
    }else{
      wx.showToast({
        icon: 'none',
        title: res.data.msg
      })
    }

    wx.hideLoading();
  }).catch(error => {

    wx.showToast({
      icon: 'none',
      title: '发起支付失败'
    })

    wx.hideLoading();
  })
}